package com.zzsy.carosshopprojects.activitys.login.vmode;

import android.content.Intent;

import com.igexin.sdk.PushManager;
import com.king.base.util.StringUtils;
import com.king.base.util.ToastUtils;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.zzsy.carosshopprojects.R;
import com.zzsy.carosshopprojects.activitys.home.mainpage.main.HomePageAc;
import com.zzsy.carosshopprojects.base.BaseViewMode;
import com.zzsy.carosshopprojects.base.ConfigureFile;
import com.zzsy.carosshopprojects.bean.LoginBean;
import com.zzsy.carosshopprojects.bean.showDataBean;
import com.zzsy.carosshopprojects.network.RequestUtils;
import com.zzsy.carosshopprojects.network.Utils.MyObserver;
import com.zzsy.carosshopprojects.util.ApkInfoUtil;
import com.zzsy.carosshopprojects.util.SPUtil;
import com.zzsy.carosshopprojects.util.ShowDialogUtils;
import com.zzsy.carosshopprojects.view.dialog.ComOneBtnDialog;

import androidx.lifecycle.MutableLiveData;
import cn.jpush.android.api.JPushInterface;

/**
 * 登录的VM
 */
public class LoginMode extends BaseViewMode {
    private boolean bln_IsFinish;//false 登录页的登录 true启动页的登录
    private static LoginMode loginMode;
    public static final int UNTREATED = -1;//不做任何处理
    public static final int SAVE = 1;//保存账号密码
    public static final int NOTSAVE = 2;//不保存账号密码
    private int state;//是否处理保存账号密码的状态
    private MutableLiveData<showDataBean> liveData;//首页列表数据

    public static LoginMode builder() {
        if (loginMode == null) {
            loginMode = new LoginMode();
        }
        return loginMode;
    }


    /**
     * 启动页传true 登录页传入false 用来判断是否finish掉activity
     *
     * @param bln_IsFinish
     */
    public LoginMode setIsFinis(boolean bln_IsFinish) {
        this.bln_IsFinish = bln_IsFinish;
        return this;
    }

    /**
     * 是否处理保存账号密码的状态
     *
     * @param state
     * @return
     */
    public LoginMode setState(int state) {
        this.state = state;
        return this;
    }

    /**
     * 登录
     *
     * @param psdStr
     * @param accountStr
     */
    public void login(RxAppCompatActivity activity, String psdStr, String accountStr) {
        if (StringUtils.isEmpty(accountStr)) {
            ToastUtils.showToast(activity.getApplicationContext(), activity.getApplicationContext().getResources().getString(R.string.error_inputAccount));
            return;
        }
        if (StringUtils.isEmpty(psdStr)) {
            ToastUtils.showToast(activity.getApplicationContext(), activity.getApplicationContext().getResources().getString(R.string.error_inputPwd));
            return;
        }
        if (state == SAVE) {
            SPUtil.getInstance().putString(ConfigureFile.ACCOUNT, accountStr);
            SPUtil.getInstance().putString(ConfigureFile.PWD, psdStr);
            SPUtil.getInstance().putBoolean(ConfigureFile.ISREMENBER, true);

        } else if (state == NOTSAVE) {
            SPUtil.getInstance().putString(ConfigureFile.PWD, "");
            SPUtil.getInstance().putBoolean(ConfigureFile.ISREMENBER, false);
        }
        String clientid = "";
        if (!ApkInfoUtil.isNetworkConnected(activity.getApplicationContext())) {
            ToastUtils.showToast(activity.getApplicationContext(), activity.getApplicationContext().getResources().getString(R.string.error_network));
            if (bln_IsFinish)
                ActivityFinish(activity);
            else {
                ShowDialogUtils.showDialogs(activity, ComOneBtnDialog.DIALOG_NOT_WIFI, -1);
            }


        } else {
            clientid = PushManager.getInstance().getClientid(activity.getApplicationContext());
            if (StringUtils.isEmpty(clientid)) {
                if (bln_IsFinish) {
                    setLoginStateQuit();
                    ActivityFinish(activity);
                }
                ToastUtils.showToast(activity.getApplicationContext(), activity.getApplicationContext().getResources().getString(R.string.error_cid));
                return;
            }
        }

        // 如果账号密码都为 oldPwd 说明是从启动页传进来进行重新登录 则获取本地存储的账号密码
        if (psdStr.equals("oldPwd") && accountStr.equals("oldPwd")) {
            psdStr = SPUtil.getInstance().getString(ConfigureFile.PWD, "");
            accountStr = SPUtil.getInstance().getString(ConfigureFile.ACCOUNT, "");
        }

        getLoginData(activity, accountStr, psdStr, clientid);
    }

    /**
     * 设置 重新登录
     */
    private void setLoginStateQuit() {
        SPUtil.getInstance().putBoolean(ConfigureFile.ISLOGIN, false);
    }

    /**
     * 进行登录接口的处理
     */
    private void getLoginData(RxAppCompatActivity activity, String accountStr, String psdStr, String clientid) {
        RequestUtils.Login(activity, accountStr, psdStr, clientid, new MyObserver<LoginBean>(activity) {
            @Override
            public void onSuccess(LoginBean loginBean) {
                setData(activity, loginBean);
            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                if (bln_IsFinish) {//启动页进来的判断
                    setLoginStateQuit();
                    ActivityFinish(activity);
                    ToastUtils.showToast(activity.getApplicationContext(), activity.getApplicationContext().getResources().getString(R.string.error_network));
                } else {//正常登录的判断
                    if (code == 700)
                        ToastUtils.showToast(activity.getApplicationContext(), activity.getApplicationContext().getResources().getString(R.string.error_network));
                    else
                        ToastUtils.showToast(activity.getApplicationContext(), errorMsg);
                }
            }
        });

    }

    /**
     * 处理登录成功的接口数据
     */
    private void setData(RxAppCompatActivity activity, LoginBean data) {

        setConfigure(data);

        String customerType = dataIsNull(data.getCustomerType());
        if (customerType.isEmpty()) {
            isStartLogin(activity);
            ToastUtils.showToast(activity.getApplicationContext(), "账号登录类型异常");
            return;
        }
        if ("0".equals(customerType)) {
            isStartLogin(activity);
            ToastUtils.showToast(activity.getApplicationContext(), "该账号类型不支持登录");
            return;
        }

        /**
         * 登录成功后保存当前的APK版本 以便用来比较更新版本后起始页是否重新登录
         */
        int CurrentVersion = ApkInfoUtil.getVersionCode(activity.getApplicationContext());
        SPUtil.getInstance().putInt(ConfigureFile.OLDVERSION, CurrentVersion);
        /**
         * 3.0 关于别名的更改：
         * 正式：merchant_v3_设备号
         * 测试:TEST3
         * */
        JPushInterface.setAlias(activity.getApplicationContext(), 0, ConfigureFile.ALIAS + dataIsNull(data.getTerminalId()));
        /*正式
         * */
        PushManager.getInstance().bindAlias(activity.getApplicationContext(), ConfigureFile.ALIAS + dataIsNull(data.getTerminalId()));
        //跳转首页页面
        activity.startActivity(new Intent(activity, HomePageAc.class));
        activity.overridePendingTransition(0, 0);
        ActivityFinish(activity);

    }

    /**
     * 保存登录返回的信息内容
     */
    public void setConfigure(LoginBean data) {
        SPUtil.getInstance().putString(ConfigureFile.JWT, dataIsNull(data.getJwt()));
        SPUtil.getInstance().putString(ConfigureFile.COMPANYID, dataIsNull(data.getCompanyId())); //  企业id
        SPUtil.getInstance().putString(ConfigureFile.STOREID, dataIsNull(data.getStoreId())); //  门店的id
        SPUtil.getInstance().putString(ConfigureFile.STORENAME, dataIsNull(data.getStoreName())); //  门店名称
        SPUtil.getInstance().putString(ConfigureFile.NAME, dataIsNull(data.getName())); //  账户名
        SPUtil.getInstance().putString(ConfigureFile.CUSTOMERTYPE, dataIsNull(data.getCustomerType()));// 账号类型 0 后台用户 1 加油员 2 吧台
        SPUtil.getInstance().putString(ConfigureFile.TERMINALNUM, dataIsNull(data.getTerminalNum())); //终端号
        SPUtil.getInstance().putString(ConfigureFile.OPENSTATE, dataIsNull(data.getOpenState()));  //终端开通状态 0未开通 1 已开通
        SPUtil.getInstance().putString(ConfigureFile.ACTIVATIONSTATE, dataIsNull(data.getActivationState())); //终端激活状态 0 未激活 1 已激活
        SPUtil.getInstance().putString(ConfigureFile.TOKEN, dataIsNull(data.getToken()));  //终端token
        SPUtil.getInstance().putString(ConfigureFile.TERMINALID, dataIsNull(data.getTerminalId())); //终端id                                                        
        SPUtil.getInstance().putString(ConfigureFile.MERCHANTNUM, dataIsNull(data.getMerchantNum()));//商户号
        SPUtil.getInstance().putString(ConfigureFile.TERMINALNAME, dataIsNull(data.getTerminalName())); //设备名称
        SPUtil.getInstance().putString(ConfigureFile.QRSWITCH, dataIsNull(data.getQrSwitch())); //开具发票开关
        SPUtil.getInstance().putString(ConfigureFile.USERID, dataIsNull(data.getUserId())); //获取用户id
        SPUtil.getInstance().putString(ConfigureFile.COMPANYNAME, dataIsNull(data.getCompanyName())); //获取集团名称
        SPUtil.getInstance().putString(ConfigureFile.ISUSERMEMBER, dataIsNull(data.getCardPayStatus())); //门店是否可以使用会员卡功能
        SPUtil.getInstance().putString(ConfigureFile.PRINTPOSTION, dataIsNull(data.getPrintPosition())); //小票使用模板
        SPUtil.getInstance().putBoolean(ConfigureFile.ISLOGIN, true); // 记录已经登录过
    }

    /**
     * 处理null数据
     */
    private String dataIsNull(String str) {
        return str == null ? "" : str;
    }

    /**
     * 是否启动页登录
     */
    private void isStartLogin(RxAppCompatActivity activity) {
        if (bln_IsFinish) {
            setLoginStateQuit();
            ActivityFinish(activity);
        }
    }

    /**
     * 返回上一页
     */
    private void ActivityFinish(RxAppCompatActivity activity) {
        activity.finish();
    }

    /**
     * 记住密码等逻辑处理 进行数据回显
     */
    public void postShowData() {
        showDataBean bean = new showDataBean();
        bean.setAccount(SPUtil.getInstance().getString(ConfigureFile.ACCOUNT, ""));
        bean.setPwd(SPUtil.getInstance().getString(ConfigureFile.PWD, ""));
        bean.setRemenber(SPUtil.getInstance().getBoolean(ConfigureFile.ISREMENBER, false));
        liveData.postValue(bean);
    }

    public MutableLiveData<showDataBean> getLive() {
        if (liveData == null)
            liveData = new MutableLiveData<>();
        return liveData;
    }


}
